package com.taotao.sso.service;

import java.util.Date;

import javax.jws.soap.SOAPBinding.Use;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.taotao.common.service.RedisService;
import com.taotao.sso.mapper.UserMapper;
import com.taotao.sso.pojo.User;

@Service
public class UserService {
	
	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private RedisService redisService;
	
	@Value("${SSO_TAOTAO_TOKEN_PREFIX}")
	private String SSO_TAOTAO_TOKEN_PREFIX;
	
	@Value("${SSO_TAOTAO_TOKEN_SECONDS}")
	private Long SSO_TAOTAO_TOKEN_SECONDS;
	
	private ObjectMapper mapper = new ObjectMapper();

	public Boolean checkUser(String param, Integer type) {
		User user = new User();
		//用户名校验
		switch(type){
		case 1:
			user.setUsername(param);
			break;
		case 2:
			user.setPhone(param);
			break;
		case 3:
			user.setEmail(param);
			break;
		default:
			return null;
		
		}
		return this.userMapper.selectCount(user)==0;
		
	}

	public Boolean register(User user) {
		//数据处理
		user.setId(null);
		user.setCreated(new Date());
		user.setUpdated(user.getCreated());
		
		//密码应该加密存储,这里使用apache的加密工具
		user.setPassword(DigestUtils.md5Hex(user.getPassword()));
		int count = userMapper.insertSelective(user);
		return count==1;
	}

	public String login(String username, String password) throws JsonProcessingException {
		//根据用户名查找用户
		User record = new User();
		record.setUsername(username);
		User user = this.userMapper.selectOne(record);
		//如果用户为null,代表用户名不存在
		if (user==null) {
			return null;
		}
		
		
		//如果密码不相等,说明密码输入有误,直接返回 null
		if (!StringUtils.equals(DigestUtils.md5Hex(password), user.getPassword())) {
			return null;
		}
		//登录成功
		
		//1.生成token,为了防止被看出规律,在用户名前后加时间戳,并用md5加密
		String token = DigestUtils.md5Hex(username + System.currentTimeMillis());
		
		//2.把用户信息序列化为json后放入redis中,这里的key直接使用token,为了和redis中其他的可以区别,所以加上前缀TOKEN_
		try {
			redisService.set(SSO_TAOTAO_TOKEN_PREFIX + token, mapper.writeValueAsString(user),SSO_TAOTAO_TOKEN_SECONDS);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return token;

	}

	public User query(String token) {
		try {
			String key = SSO_TAOTAO_TOKEN_PREFIX+token;
			User user = redisService.get(key, new TypeReference<User>() {
			});
			if (user != null) {
				//刷新用户生存时间
				this.redisService.expire(key, SSO_TAOTAO_TOKEN_SECONDS);
				return user;
			} 
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
		
	}
}
